home *** CD-ROM | disk | FTP | other *** search
- Path: news.us.net!usenet
- From: thoth256@us.net (Evelio Perez-Albuerne)
- Newsgroups: comp.lang.c++
- Subject: Re: Will it be auto-deleted?
- Date: Mon, 26 Feb 1996 14:20:16 GMT
- Organization: US Net
- Message-ID: <4gsff2$21k@news.us.net>
- References: <1996Feb20.110314.46035@yogi.urz.unibas.ch> <4gg91j$gdc@clarknet.clark.net>
- NNTP-Posting-Host: thoth256.laurel.us.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- gusty@clark.net (Harlan Messinger) wrote:
-
- >Song Jin (song@iso.iso.unibas.ch) wrote:
- >: I have a question:
- >:
- >: void myfunction(void)
- >: {
- >: double *mypointer = new double[100];
- >:
- >: .....
- >:
- >: }
- >:
- >: The mypointer and the buffer it pointed will be auto-deleted after returned
- >: from myfunction, am I right?
- >:
-
- >Absolutely not. Any memory allocated with new has to be deleted
- >explicitly.
-
- > delete [] mypointer;
-
- >Otherwise, once all pointers to it have gone out of scope, it'll just sit
- >there unreachable until the heap itself is returned to wherever it came
- >from (if that happens) or garbage collection returns it to the heap (if
- >your system has garbage collection) or until the machine is rebooted. This
- >is called a "memory leak".
-
- An alternative to manually deleteing the pointer is to use an
- auto_array<T> class instead of a plain function pointer. This class is
- very similar to the auto_ptr<T> class which I know is being included
- in the Standard C++ Library. I don't know if auto_array<T> is also
- part of the SC++L, but it is obviously needed since "delete []" not
- plain "delete" needs to be called.
-
- Here is my implementation of auto_array<T>:
-
- template <class T>
- class auto_array
- {
- public:
- auto_array(T* pp = 0) : p(pp) {}
- auto_array(auto_array<T>& x) : p(x.p) {x.p = 0;}
- ~auto_array() {delete [] p;}
-
- T& operator [](int i) {return p[i];}
- auto_array<T>& operator =(T* pp) {delete [] p; p = pp; return *this;}
- auto_array<T>& operator =(auto_array<T>& x)
- {delete [] p; p = x.p; x.p = 0; return *this;}
- T* get() {return p;}
- T* release() {T* pp = p; p = 0; return pp;}
-
- private:
- T* p;
- };
-
- Use it like this:
-
- void myfunction(void)
- {
- auto_array<double> mypointer(new double[100]);
-
- .....
-
- }
-
- Now the array will automatically be deleted when mypointer goes out of
- scope. Hope this helps!
-
- ********************************************************
- Evelio Perez-Albuerne <thoth256@us.net>
-
-